﻿#include "Base64Test.h"

#ifdef WIN32
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <stdarg.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "Base64.h"
#include "time.h"
#include <sstream>
#include <cstdio>
#include <iostream>

Base64Test::Base64Test(void)
{
}


Base64Test::~Base64Test(void)
{
}

void Base64Test::test()
{
    std::string strText = "this is a test";
    std::string strBase;
    std::string strHex;

    Base64Encode(strText,&strBase);
    std::cout<<"debug 001 : "<<strBase<<std::endl;
    strHex = convertToHex(strBase);

    std::cout<<"debug 002 : "<<strHex<<std::endl;

    std::string strBaseAgain = convertFromHex(strHex);
    std::string strTextAgain;
    Base64Decode(strBaseAgain,&strTextAgain);
    std::cout<<"debug 003 : "<<strTextAgain<<std::endl;

}
void Base64Test::printString( std::string strText )
{
	int n = strText.length();
    std::cout<<"打印:"<<strText<<std::endl;
	for (int index = 0; index < n; index++)
	{
		unsigned char ch = strText.c_str()[index];
		printf("%.2x,",ch);
	}
	printf("\n");
}

std::string Base64Test::convertToHex(const std::string &strData )
{
	static const char* const lut = "0123456789ABCDEF";
    size_t len = strData.length();
	std::string output;
	output.reserve(2 * len);
	for (size_t i = 0; i < len; ++i)
	{
        const unsigned char c = strData[i];
		output.push_back(lut[c >> 4]);
		output.push_back(lut[c & 15]);
	}
	return output;
}

std::string Base64Test::convertFromHex(const std::string &strData )
{
	static const char* const lut = "0123456789ABCDEF";
    size_t len = strData.length();
	if (len & 1) throw std::invalid_argument("odd length");
	std::string output;
	output.reserve(len / 2);
	for (size_t i = 0; i < len; i += 2)
	{
        char a = strData[i];
		const char* p = std::lower_bound(lut, lut + 16, a);
		if (*p != a) throw std::invalid_argument("not a hex digit");
        char b = strData[i + 1];
		const char* q = std::lower_bound(lut, lut + 16, b);
		if (*q != b) throw std::invalid_argument("not a hex digit");
		output.push_back(((p - lut) << 4) | (q - lut));
	}
	return output;
}
